package com.doubao.wechat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.common.result.Result;
import com.doubao.wechat.dto.request.WxPayOrderRequest;
import com.doubao.wechat.entity.PaymentOrder;
import com.doubao.wechat.mapper.PaymentOrderMapper;
import com.doubao.wechat.service.PaymentOrderService;
import com.doubao.wechat.service.WechatService;
import com.doubao.wechat.util.OrderNumberUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 支付订单服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class PaymentOrderServiceImpl extends ServiceImpl<PaymentOrderMapper, PaymentOrder> implements PaymentOrderService {

    private final PaymentOrderMapper paymentOrderMapper;
    private final WechatService wechatService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<PaymentOrder> createOrder(Long userId, Long productId, Integer amount,
                                            String subject, String body, String payChannel,
                                            String payType, String attach, String clientIp) {
        try {
            // 生成商户订单号
            String outTradeNo = OrderNumberUtil.generatePaymentOrderNumber();

            // 创建支付订单
            PaymentOrder paymentOrder = new PaymentOrder();
            paymentOrder.setId(outTradeNo); // 使用商户订单号作为主键
            paymentOrder.setUserId(userId);
            paymentOrder.setProductId(productId);
            paymentOrder.setAmount(amount);
            paymentOrder.setPayChannel(payChannel);
            paymentOrder.setPayType(payType);
            paymentOrder.setOutTradeNo(outTradeNo);
            paymentOrder.setStatus("WAIT_PAY");
            paymentOrder.setSubject(subject);
            paymentOrder.setBody(body);
            paymentOrder.setAttach(attach);
            paymentOrder.setClientIp(clientIp);
            paymentOrder.setRefundStatus(0);
            paymentOrder.setRefundAmount(0);
            paymentOrder.setCreatedAt(LocalDateTime.now());
            paymentOrder.setUpdatedAt(LocalDateTime.now());

            // 设置过期时间，默认2小时后过期
            paymentOrder.setExpireTime(LocalDateTime.now().plusHours(2));

            // 保存支付订单
            save(paymentOrder);

            return Result.success(paymentOrder);
        } catch (Exception e) {
            log.error("创建支付订单异常", e);
            return Result.failed("创建支付订单异常：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> updateOrderStatus(String outTradeNo, String status, String tradeNo) {
        try {
            // 查询订单
            PaymentOrder paymentOrder = paymentOrderMapper.selectByOutTradeNo(outTradeNo);
            if (paymentOrder == null) {
                return Result.failed("订单不存在");
            }

            // 更新订单状态
            paymentOrder.setStatus(status);
            paymentOrder.setTradeNo(tradeNo);
            paymentOrder.setUpdatedAt(LocalDateTime.now());

            // 如果是支付成功，设置支付时间
            if ("SUCCESS".equals(status)) {
                paymentOrder.setPayTime(LocalDateTime.now());
            }

            // 更新订单
            updateById(paymentOrder);

            return Result.success();
        } catch (Exception e) {
            log.error("更新支付订单状态异常", e);
            return Result.failed("更新支付订单状态异常：" + e.getMessage());
        }
    }

    @Override
    public Result<PaymentOrder> getOrderByOutTradeNo(String outTradeNo) {
        try {
            PaymentOrder paymentOrder = paymentOrderMapper.selectByOutTradeNo(outTradeNo);
            if (paymentOrder == null) {
                return Result.failed("订单不存在");
            }
            return Result.success(paymentOrder);
        } catch (Exception e) {
            log.error("查询支付订单异常", e);
            return Result.failed("查询支付订单异常：" + e.getMessage());
        }
    }

    @Override
    public Result<List<PaymentOrder>> getUserOrders(Long userId, String status) {
        try {
            LambdaQueryWrapper<PaymentOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PaymentOrder::getUserId, userId);

            // 如果状态不为空，添加状态条件
            if (status != null) {
                wrapper.eq(PaymentOrder::getStatus, status);
            }

            // 按创建时间降序排序
            wrapper.orderByDesc(PaymentOrder::getCreatedAt);

            List<PaymentOrder> orderList = list(wrapper);
            return Result.success(orderList);
        } catch (Exception e) {
            log.error("查询用户支付订单列表异常", e);
            return Result.failed("查询用户支付订单列表异常：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> closeOrder(String outTradeNo) {
        try {
            // 查询订单
            PaymentOrder paymentOrder = paymentOrderMapper.selectByOutTradeNo(outTradeNo);
            if (paymentOrder == null) {
                return Result.failed("订单不存在");
            }

            // 检查订单状态
            if (!"WAIT_PAY".equals(paymentOrder.getStatus())) {
                return Result.failed("订单状态不允许关闭");
            }

            // 更新订单状态为已关闭
            paymentOrder.setStatus("CLOSED");
            paymentOrder.setUpdatedAt(LocalDateTime.now());
            updateById(paymentOrder);

            return Result.success();
        } catch (Exception e) {
            log.error("关闭支付订单异常", e);
            return Result.failed("关闭支付订单异常：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> handleOrderExpire(String outTradeNo) {
        try {
            // 查询订单
            PaymentOrder paymentOrder = paymentOrderMapper.selectByOutTradeNo(outTradeNo);
            if (paymentOrder == null) {
                return Result.failed("订单不存在");
            }

            // 检查订单状态
            if (!"WAIT_PAY".equals(paymentOrder.getStatus())) {
                return Result.failed("订单状态不需要处理过期");
            }

            // 检查是否已过期
            if (paymentOrder.getExpireTime().isAfter(LocalDateTime.now())) {
                return Result.failed("订单尚未过期");
            }

            // 更新订单状态为已关闭
            paymentOrder.setStatus("CLOSED");
            paymentOrder.setUpdatedAt(LocalDateTime.now());
            updateById(paymentOrder);

            // 调用微信支付关闭订单
            // 注意：这里可能会失败，但不影响我们自己的订单状态变更
            try {
                // wxPayService.closeOrder(outTradeNo);
            } catch (Exception e) {
                log.warn("调用微信支付关闭订单失败，outTradeNo={}", outTradeNo, e);
            }

            return Result.success();
        } catch (Exception e) {
            log.error("处理订单过期异常", e);
            return Result.failed("处理订单过期异常：" + e.getMessage());
        }
    }

    @Override
    public WxPayOrderRequest createWxPayRequest(PaymentOrder paymentOrder, String openid) {
        WxPayOrderRequest request = new WxPayOrderRequest();
        request.setOutTradeNo(paymentOrder.getOutTradeNo());
        request.setOpenid(openid);
        request.setTotalAmount(paymentOrder.getAmount());
        request.setDescription(paymentOrder.getBody());
        request.setAttach(paymentOrder.getAttach());
        request.setClientIp(paymentOrder.getClientIp());

        // 根据支付类型设置交易类型
        if ("jsapi".equalsIgnoreCase(paymentOrder.getPayType()) || "miniapp".equalsIgnoreCase(paymentOrder.getPayType())) {
            request.setTradeType("jsapi");
        } else {
            request.setTradeType(paymentOrder.getPayType());
        }

        return request;
    }
}